package com.liangxy.zhyl.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

@MappedTypes(Set.class)
public class SetTypeHandler extends BaseTypeHandler<Set<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Set<String> parameter, JdbcType jdbcType) throws SQLException {
        // 将Set转换为逗号分隔的字符串存储，如："role1,role2,role3"
        if (parameter == null || parameter.isEmpty()) {
            ps.setString(i, "");
        } else {
            String joinedString = String.join(",", parameter);
            ps.setString(i, joinedString);
        }
    }

    @Override
    public Set<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String dbValue = rs.getString(columnName);
        return convertToSet(dbValue);
    }

    @Override
    public Set<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String dbValue = rs.getString(columnIndex);
        return convertToSet(dbValue);
    }

    @Override
    public Set<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String dbValue = cs.getString(columnIndex);
        return convertToSet(dbValue);
    }

    private Set<String> convertToSet(String dbValue) {
        if (dbValue == null || dbValue.trim().isEmpty()) {
            return new HashSet<>();
        }
        // 按逗号分割并去除空格
        return Arrays.stream(dbValue.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toSet());
    }
}
